import { type NextRequest, NextResponse } from "next/server"
import { authenticateUser } from "@/lib/db-sqlite"
import { cookies } from "next/headers"

export async function POST(request: NextRequest) {
  try {
    const { username, password } = await request.json()

    if (!username || !password) {
      return NextResponse.json({ error: "用户名和密码不能为空" }, { status: 400 })
    }

    const user = authenticateUser(username, password)

    if (!user) {
      return NextResponse.json({ error: "用户名或密码错误" }, { status: 401 })
    }

    // 创建会话
    const sessionId = crypto.randomUUID()

    // 设置会话 cookie
    cookies().set({
      name: "admin_session",
      value: sessionId,
      httpOnly: true,
      path: "/",
      sameSite: "lax",
      secure: process.env.NODE_ENV === "production",
      maxAge: 60 * 60 * 24 * 7, // 7 天
    })

    // 返回用户信息（不包含密码）
    return NextResponse.json({
      user: {
        id: user.id,
        name: user.name,
        role: user.role,
      },
      success: true,
    })
  } catch (error: any) {
    console.error("Authentication error:", error)
    return NextResponse.json({ error: error.message || "认证失败" }, { status: 500 })
  }
}

export async function DELETE(request: NextRequest) {
  // 清除会话 cookie
  cookies().delete("admin_session")

  return NextResponse.json({ success: true })
}
